package mt.server;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import mt.Order;
import mt.comm.ServerComm;
import mt.comm.ServerSideMessage;

public class RunnableServer implements Runnable {

	private ServerComm serverComm;
	private HashMap<Integer, Order> SellOrders;
	private HashMap<Integer, Order> buyOrders;
	private static int totalOrderNumber = 0;
	private Set<String> clients;

	public RunnableServer(ServerComm serverComm) {
		this.serverComm = serverComm;
		this.SellOrders = new HashMap<Integer, Order>();
		this.buyOrders = new HashMap<Integer, Order>();
		this.clients = new HashSet<String>();
	}

	@Override
	public void run() {
		if (serverComm.hasNextMessage()) {
			ServerSideMessage newMessage = serverComm.getNextMessage();
			processReceivedMessage(newMessage);
		}
	}
		private void processReceivedMessage(ServerSideMessage newMessage) {
			if (newMessage != null) {
				// processar a mensagem
				Order currentOrder = newMessage.getOrder();
				boolean updatedOrder = updateOrder(currentOrder);
				/*	matchOrders
			matchOrders(currentOrder);
			updateClients();
				 */
			}
		}
			private boolean updateOrder(Order currentOrder) {
				if (currentOrder.getServerOrderID() == 0) {//recebemos nova ordem
					++totalOrderNumber;
					currentOrder.setServerOrderID(totalOrderNumber);
					addClient(currentOrder.getNickname());
					return false;
				} else {
					if (currentOrder.isBuyOrder()) {//update order
						this.buyOrders.put(currentOrder.getServerOrderID(),
								currentOrder);
					}
					return true;
				}
			}
				private void checkConections(){
					/*desconectar

					 * remover o cliente do hashset

					 * remover as orders*/


					for(String client:this.clients){

						if(!serverComm.clientIsConnected(client)){

							serverComm.disconnectClient(client);

							Iterator<Order> selIt = SellOrders.values().iterator();

							while (selIt.hasNext()){

								Order order = selIt.next();

								if (order.getNickname().compareTo(client)==0){

									SellOrders.remove(order.getServerOrderID());

								}

							}

							Iterator<Order> buyIt = buyOrders.values().iterator();

							while(buyIt.hasNext()){

								Order order = buyIt.next();

								if(order.getNickname().compareTo(client)==0){

									buyOrders.remove(order.getServerOrderID());

								}
							}
						}
					}

				}
				private void addClient(String nickname) {
					// TODO Auto-generated method stub
					if (nickname != null)
						this.clients.add(nickname);
				}

			}
